#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include "log.hpp"
#include "dict.hpp"
extern Log lg;

Dict dict;

class Task
{
public:
    Task(int sockfd, const std::string &clientip, const uint16_t clientport) //默认构造
    :_sockfd(sockfd), _ip(clientip), _port(clientport)
    {}
    ~Task()
    {}

    void Run()
    {
        //service方法
        char buffer[4096] = { 0 };
        ssize_t n = read(_sockfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say# " << buffer << std::endl; //打印在服务端的
            //std::string echo_string = "tcpserver echo# ";
            std::string echo_string = dict.translation(buffer);
            //echo_string += buffer;

            int ret_wrt = write(_sockfd, echo_string.c_str(), echo_string.size());
            if(ret_wrt < 0)
            {
                lg(Warning, "write error, errno : %d, errstring: %s", errno, strerror(errno));
            }
        }
        else if (n == 0)
        {
            lg(Info, "%s:%d quit, server close sockfd: %d", _ip.c_str(), _port, _sockfd);
        }
        else
        {
            lg(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", _ip, _ip.c_str(), _port);
        }
        close(_sockfd); //服务完一次就关闭
    }

    void operator()() //仿函数调用
    {
        Run();
    }

private:
    int _sockfd;
    const std::string& _ip;
    const uint16_t _port;

};